package cn.ldf.keepaccounts.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cn.ldf.keepaccounts.constant.BaseConstant;
import cn.ldf.keepaccounts.entity.dto.AvatarFileDTO;
import cn.ldf.keepaccounts.entity.pojo.Users;
import cn.ldf.keepaccounts.entity.vo.R;
import cn.ldf.keepaccounts.entity.vo.WxUserVO;
import cn.ldf.keepaccounts.service.GameRecordsService;
import cn.ldf.keepaccounts.service.MembersService;
import cn.ldf.keepaccounts.service.RoomsService;
import cn.ldf.keepaccounts.service.UsersService;
import cn.ldf.keepaccounts.utils.ExceptionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * 用户表(Users)表控制层
 *
 * @author 清峰
 * @since 2025-02-17 10:16:42
 */
@RestController
@RequestMapping("users")
public class UsersController {

    @Resource
    private UsersService usersService;

    @Value("${app.accessKey}")
    private String accessKey;

    /**
     * 新增用户
     *
     * @param users 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R<Users> insertUsers(@Valid @RequestBody Users users) {
        return R.success(this.usersService.insertUsers(users));
    }

    /**
     * 上传头像
     *
     * @param avatarFileDTO 头像文件
     * @return 结果集
     */
    @PostMapping("/uploadBaseAvatar")
    public R<Boolean> uploadBaseAvatar(@Valid @RequestBody AvatarFileDTO avatarFileDTO) {
        String contentType = avatarFileDTO.getContentType();
        ExceptionUtil.throwMsg(() -> !BaseConstant.IMAGES_TYPE.contains(contentType), "上传图片类型不符合要求");
        String avatarBase64 = avatarFileDTO.getAvatarBase64();
        byte[] avatarByte = Base64Decoder.decode(avatarBase64);
        ExceptionUtil.throwMsg(() -> avatarByte.length > 1024 * 1024, "上传图片大小不能超过1M");
        return R.success(usersService.uploadBaseAvatar(avatarByte, contentType, avatarFileDTO.getOpenId(), avatarFileDTO.getNickname()));
    }

    /**
     * 【登陆】用微信授权码code换取openId
     *
     * @param code 用户openId
     * @return 结果集
     */
    @GetMapping("/getOpenIdByCode")
    public R<WxUserVO> getOpenIdByCode(@RequestParam String code) {
        WxUserVO wxUserVO = usersService.getOpenIdByCode(code);
        StpUtil.login(wxUserVO.getOpenid());
        wxUserVO.setTokenName(StpUtil.getTokenName());
        wxUserVO.setTokeValue(StpUtil.getTokenValue());
        return R.data(wxUserVO);
    }

    /**
     * 【注销】退出登陆
     *
     * @return 结果集
     */
    @GetMapping("/login")
    public R<WxUserVO> logout() {
        StpUtil.logout();
        return R.success("注销成功");
    }

    /**
     * 根据密钥信息创建调试token
     *
     * @param accessKey 用户 accessKey
     * @return 结果集
     */
    @GetMapping("/createToken")
    public R<String> createToken(@RequestParam String accessKey) {
        ExceptionUtil.throwMsg(() -> !accessKey.equals(this.accessKey), "accessKey错误");
        StpUtil.login(accessKey);
        return R.data(StpUtil.getTokenValue());
    }

    /**
     * 根据openId查询用户是否存在
     *
     * @param openId 用户openId
     * @return 结果集
     */
    @GetMapping("/isExist/{openId}")
    public R<Boolean> isExistByOpenId(@PathVariable String openId) {
        return R.success(usersService.isExistByOpenId(openId));
    }

    /**
     * 根据openId查询用户信息(含头像)
     *
     * @param openId 用户openId
     * @return 结果集
     */
    @GetMapping("/getByOpenId/{openId}")
    public R<Users> getByOpenId(@PathVariable String openId) {
        return R.data(usersService.getByOpenId(openId));
    }

    /**
     * 根据openId查询用户(不含头像)
     *
     * @param openId 用户openId
     * @return 结果集
     */
    @GetMapping("/selectOneByOpenId/{openId}")
    public R<Users> selectOneByOpenId(@PathVariable String openId) {
        return R.success(this.usersService.selectOneByOpenId(openId));
    }


    @Resource
    private RoomsService roomsService;
    @Resource
    private MembersService membersService;
    @Resource
    private GameRecordsService gameRecordsService;

    /**
     * 删除所有数据
     *
     * @return 结果集
     */
    @GetMapping("deleteAllData")
    public R<?> deleteAllData(@RequestParam(required = false) String openId) {
        if (StrUtil.isNotBlank(openId)) {
            usersService.lambdaUpdate().eq(Users::getOpenId, openId).remove();
        } else {
            usersService.remove(new QueryWrapper<>());
        }
        membersService.remove(new QueryWrapper<>());
        gameRecordsService.remove(new QueryWrapper<>());
        roomsService.remove(new QueryWrapper<>());
        return R.success("数据删除成功");
    }



}

